import React, { useEffect, useState } from "react";
import { Card, Button, Table, Input, message, Form, Modal, Select } from "antd";
import { PlusOutlined } from "@ant-design/icons";
import axios from "axios";
import { connect } from "react-redux";

const { Option } = Select;

const Category = (props) => {
  const { userInfo } = props;
  const [form] = Form.useForm();

  let [isLoading, setIsLoading] = useState(true);
  let [categoryList, setCategoryList] = useState([]);
  let [isModalVisible, setIsModalVisible] = useState(false);
  let [id, setId] = useState("");
  let [operationType, setOperationType] = useState("add");
  let [initName, setInitName] = useState("");
  let [initPid, setInitPid] = useState("");

  const reqcategoryList = async (current, name, email) => {
    try {
      const responce = await axios.get(
        "http://api.shop.eduwork.cn/api/admin/category",

        {
          headers: {
            Authorization: userInfo.token,
          },
        }
      );

      setIsLoading(false);
      setCategoryList(responce.data);
    } catch (err) {
      message.error(err.message);
    }
  };

  const reqAddCategory = async (values) => {
    try {
      const responce = await axios.post(
        "http://api.shop.eduwork.cn/api/admin/category",
        values,

        {
          headers: {
            Authorization: userInfo.token,
          },
        }
      );

      if (responce.status === 201) {
        message.success("添加商品分类成功");
      }

      form.resetFields();
      setIsModalVisible(false);
    } catch (err) {
      message.error("不能超过二级分类");
    }
  };

  const reqUpdateCategory = async (values) => {
    try {
      const responce = await axios.put(
        `http://api.shop.eduwork.cn/api/admin/category/${id}`,
        values,

        {
          headers: {
            Authorization: userInfo.token,
          },
        }
      );

      if (responce.status === 204) {
        message.success("更新商品分类成功");
      }

      form.resetFields();
      setIsModalVisible(false);
    } catch (err) {
      message.error("不能超过二级分类");
    }
  };

  useEffect(() => {
    reqcategoryList();
    // eslint-disable-next-line
  }, []);

  const showAdd = () => {
    setOperationType("add");
    setIsModalVisible(true);
  };

  const showUpdate = (item) => {
    setOperationType("update");
    setId(item.id);
    setInitPid(item.pid);
    setInitName(item.name);
    setIsModalVisible(true);
  };

  const handleCancel = () => {
    form.resetFields();
    setIsModalVisible(false);
  };

  const onFinish = (values) => {
    if (operationType === "add ") {
      reqAddCategory(values);
    } else {
      reqUpdateCategory(values);
    }
  };

  const columns = [
    {
      title: "分类名称",
      dataIndex: "name",
      key: "name",
    },

    {
      title: "操作",
      // dataIndex: "created_at",
      align: "center",
      key: "operation",
      render: (item) => {
        return (
          <Button
            type="link"
            onClick={() => {
              showUpdate(item);
            }}
          >
            编辑
          </Button>
        );
      },
    },
  ];

  const formItemLayout = {
    labelCol: {
      xs: {
        span: 24,
      },
      sm: {
        span: 4,
      },
    },
    wrapperCol: {
      xs: {
        span: 24,
      },
      sm: {
        span: 16,
      },
    },
  };

  return (
    <div>
      <Card
        extra={
          <Button type="primary" onClick={showAdd}>
            <PlusOutlined />
            新增分类
          </Button>
        }
        loading={isLoading}
      >
        <Table
          dataSource={categoryList}
          columns={columns}
          rowKey="id"
          pagination={{
            pageSize: 5,
          }}
        />
      </Card>

      <Modal
        title={operationType === "add" ? "新增分类" : "修改分类"}
        visible={isModalVisible}
        onCancel={handleCancel}
        footer={null}
      >
        <Form
          form={form}
          name="addCategory"
          {...formItemLayout}
          onFinish={onFinish}
          initialValues={{ pid: initPid, name: initName }}
        >
          <Form.Item name="pid" label="父级分类">
            <Select placeholder="select category_id">
              <Option key={0} value={0}>
                根目录
              </Option>
              {categoryList.map((item) => {
                return (
                  <Option key={item.id} value={item.id}>
                    {item.name}
                  </Option>
                );
              })}
            </Select>
          </Form.Item>

          <Form.Item
            name="name"
            label="分类名称"
            rules={[
              {
                required: true,
                message: "Please input your username!",
              },
            ]}
          >
            <Input />
          </Form.Item>

          <Form.Item
            wrapperCol={{
              span: 12,
              offset: 4,
            }}
          >
            <Button type="primary" htmlType="submit">
              提交
            </Button>
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};

export default connect((state) => ({ userInfo: state.userInfo }))(Category);
